# -*- coding: utf-8 -*-
import pandas as pd
from utils.commons import retry_wrapper

def update_symbol_info(exchange, symbol_list):
    # 获取原始数据
    position_risk = retry_wrapper(exchange.fapiPrivateV2_get_positionrisk, func_name='获取账户持仓风险')
    position_risk = pd.DataFrame(position_risk)  # 将数据转成DataFrame
    if len(symbol_list) > 0:
        position_risk = position_risk[position_risk['symbol'].isin(symbol_list)]  # 只对选币池中的币种进行调整页面杠杆
    position_risk.rename(columns={'positionAmt': '当前持仓量'}, inplace=True)
    position_risk = position_risk[position_risk['当前持仓量'] != 0]  # 只保留有仓位的币种
    position_risk.set_index('symbol', inplace=True)  # 将symbol设置为index

    # 创建symbol_info
    symbol_info = pd.DataFrame(index=symbol_list, columns=['当前持仓量'])
    symbol_info['当前持仓量'] = position_risk['当前持仓量']
    symbol_info['当前持仓量'].fillna(value=0, inplace=True)

    return symbol_info
# =====获取持仓
# 获取币安账户的实际持仓
def get_position_df(exchange):
    """
    获取币安账户的实际持仓

    :param exchange:        交易所对象，用于获取数据
    :return:

              当前持仓量   均价  持仓盈亏
    symbol
    RUNEUSDT       -82.0  1.208 -0.328000
    FTMUSDT        523.0  0.189  1.208156

    """
    # 获取原始数据
    position_df = retry_wrapper(exchange.fapiPrivateV2_get_positionrisk, func_name='获取账户持仓风险')
    position_df = pd.DataFrame(position_df, dtype='float')    # 将原始数据转化为dataframe

    # 整理数据
    columns = {'positionAmt': '当前持仓量', 'entryPrice': '均价', 'unRealizedProfit': '持仓盈亏', 'markPrice': '当前标记价格'}
    position_df.rename(columns=columns, inplace=True)
    position_df = position_df[position_df['当前持仓量'] != 0]  # 只保留有仓位的币种
    position_df.set_index('symbol', inplace=True)  # 将symbol设置为index

    # 保留指定字段
    position_df = position_df[['当前持仓量', '均价', '持仓盈亏', '当前标记价格']]

    return position_df


# 通过持仓数据和选币下单数据估算当前各offset盈亏
def calc_offset_position_profit(order_df, position_df):
    """
    通过持仓数据和选币下单数据估算当前各offset盈亏

    :param order_df:       选币下单数据
    :param position_df:     当前持仓数据
    :return:

    """
    # 将持仓数据合并到老的下单数据中，可估算平仓收益
    df = pd.merge(left=order_df, right=position_df, on='symbol', how='left')
    df['实际持仓'] = df['持仓占比'] * df['当前持仓量']
    df['预估盈亏'] = (df['当前标记价格'] - df['close']) * df['实际持仓']

    return df
